# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
from django import forms
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.template import RequestContext
from django.utils.translation import ugettext as _
from django.views.decorators.http import require_POST
from django.core.paginator import Paginator
from django.db.models import Count
import os
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from registration.forms import RegistrationForm

from django_openid.models import UserOpenidAssociation

class OpenIDForm(RegistrationForm):
    
    def __init__(self, request, *args, **kwargs):
        super(OpenIDForm, self).__init__(*args, **kwargs)
        del self.fields['password1']
        del self.fields['password2']
        self.request = request
        
    def clean(self):
        return self.cleaned_data
    
    def save(self):
        new_user = User.objects.create_user(username = self.cleaned_data['username'], email = self.cleaned_data['email'])
        associate = UserOpenidAssociation.objects.create(openid = self.request.openid.openid, user = new_user)
        
        return new_user


def openid_account_create(request):
    if not request.openid:
        return Http404
    if request.method == 'POST':
        form = OpenIDForm(request, request.POST)
        if form.is_valid():
            user = form.save()
            return HttpResponseRedirect('/')
    else:
        username = request.openid.sreg.get('nickname', '')
        email = request.openid.sreg.get('email', '')
        form = OpenIDForm(request, initial = {'username': username, 'email': email})
        
    return render_to_response('openid_account_create.html', locals(), context_instance = RequestContext(request))